<!--
 * @Author: 严晗 823841034@qq.com
 * @Date: 2023-10-09 14:41:42
 * @LastEditors: 严晗 823841034@qq.com
 * @LastEditTime: 2023-10-12 16:36:21
 * @FilePath: /yike-admin/Users/yanhan/vite-project/src/pages/login/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
	<el-row class="bg-blue-500 min-h-screen">
		<el-col :lg="16" :md="12" class="flex flex-col justify-center items-center">
			<el-image style="width: 140px; height: 140px" src="/logo.png" fit="contain" />
			<div class="text-light-50 text-3xl font-medium mt-4">上海知渔OA系统</div>
		</el-col>
		<el-col :lg="8" :md="12" class="bg-light-50 flex flex-col justify-center items-center">
			<div class="flex items-center justify-center my-5 text-gray-300 space-x-2">
				<span class="h-[1px] w-16 bg-gray-300"></span>
				<span>账号密码登录</span>
				<span class="h-[1px] w-16 bg-gray-300"></span>
			</div>
			<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" class="w-[250px]">
				<el-form-item prop="name">
					<el-input v-model="ruleForm.name" placeholder="请输入账号">
						<template #prefix>
							<el-icon class="el-input__icon"><user /></el-icon>
						</template>
					</el-input>
				</el-form-item>
				<el-form-item prop="password">
					<el-input v-model="ruleForm.password" placeholder="请输入密码" type="password">
						<template #prefix>
							<el-icon class="el-input__icon"><lock /></el-icon>
						</template>
					</el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" round :loading="loading" color="rgb(59, 130, 246)" @click="submitForm()" class="w-[250px]"> 登录 </el-button>
				</el-form-item>
			</el-form>
		</el-col>
	</el-row>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeUnmount } from 'vue'
import { toast } from '~/composables/utils'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

const store = useStore()
const router = useRouter()

// 定义form表单里面的值
const ruleForm = reactive({
	name: '',
	password: '',
})
// 定义校验规则
const rules = reactive({
	name: [{ required: true, message: '请输入账号', trigger: 'blur' }],
	password: [
		{
			required: true,
			message: '请输入密码',
			trigger: 'blur',
		},
	],
})

// 双向绑定form表单的ref值
const ruleFormRef = ref(null)
const loading = ref(false)
// 点击登录按钮时触发
const submitForm = () => {
	// 通过form表单的ref值进行校验
	if (!ruleFormRef.value) return
	ruleFormRef.value.validate((valid, fields) => {
		if (valid) {
			loading.value = true
			store.dispatch('login', ruleForm).then(() => {
				// 提示
				toast('登录成功')

				// 跳转到首页
				router.push('/')
			}).finally(() => {
				loading.value = false
			})
		} else {
			return false
		}
	})
}

// 回车登录
function onKeyUp(e) {
	if(e.key === 'Enter') submitForm()
}
// 在页面加载完成后执行的生命周期
onMounted(() => {
	document.addEventListener('keyup', onKeyUp)
})
// 页面卸载时执行的生命周期
onBeforeUnmount(() => {
	document.removeEventListener('keyup', onKeyUp)
})

</script>
